<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :width="setDialogWidth('1000px')"
      :visible="visible"
      :title="title"
      @open="open"
      @close="close"
    >
      <el-form
        ref="cableForm"
        label-width="auto"
        size="mini"
        :model="formData"
        :rules="rules"
        class="pr-40 help-box"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('CABLE_NAME')" prop="cableName">
              <el-input
                v-model.trim="formData.cableName"
                maxlength="50"
                :readonly="type === 'view'"
                :placeholder="$t('ENTER_CABLE_NAME')"
              />
            </el-form-item>
            <el-form-item :label="$t('CABLE_LEVEL')" prop="cableLevel">
              <el-select
                v-model="formData.cableLevel"
                :disabled="type === 'view'"
              >
                <el-option
                  v-for="item in dictCableLevelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <i class="el-icon-edit-outline text-color form-tips edit-icon" @click="showLevelEdit = true" />
            </el-form-item>
            <el-form-item :label="$t('CABLE_TYPE')" prop="cableType">
              <el-select v-model="formData.cableType" :disabled="type === 'view'">
                <el-option
                  v-for="item in dictList.CABLE_TYPE"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('CABLE_MODEL')" prop="model">
              <el-input
                v-model="formData.model"
                maxlength="32"
                :readonly="type === 'view'"
                :placeholder="$t('PLEASE_ENTER_MODEL')"
              />
            </el-form-item>
            <el-form-item :label="$t('CABLE_SPE')" prop="cableNorm">
              <el-select v-model="formData.cableNorm" :disabled="type === 'view'">
                <el-option
                  v-for="item in dictList.CABLE_NORM"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('FIBER_CORE_TYPE')" prop="fiberType">
              <el-select v-model="formData.fiberType" :disabled="type === 'view'">
                <el-option
                  v-for="item in dictList.FIBER_TYPE"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('CABLE_LENGTH')" prop="cableLength">
              <el-input v-model="formData.cableLength" :disabled="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('A_END_REGIONAL_STATION_NAME')" prop="startStationId">
              <el-input v-model="formData.startStationId" class="hide" />
              <region-cascader
                class="block size-mini"
                :selected-ids="[formData.startStationId]"
                :clearable="false"
                :disabled="
                  type === 'view' ||
                    (type === 'mod' &&
                      (aStationData.status === 'CONSIGN' ||
                        aStationData.status === 'REPAIR'))
                "
                data-name="stationTree"
                @change="aStationChange"
              />
            </el-form-item>
            <el-form-item v-if="aRoomList.length" :label="$t('A_END_ROOM_NAME')">
              <el-select
                v-model="formData.startRoomId"
                clearable
                :disabled="type === 'view'"
              >
                <el-option
                  v-for="item in aRoomList"
                  :key="item.regionId"
                  :value="item.regionId"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('NOMINAL_CAPACITY')" prop="capacity">
              <el-input v-model="formData.capacity" :disabled="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('CONNECTED_NUMBER')" prop="connNum">
              <el-input v-model="formData.connNum" :disabled="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('NUMBER_TAKEUP')" prop="occupyNum">
              <el-input v-model="formData.occupyNum" :disabled="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('NUMBER_IDLE')" prop="idleNum">
              <el-input v-model="formData.idleNum" :disabled="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('RESOURCE_CODE')" prop="resourceCode">
              <el-input
                v-model="formData.resourceCode"
                maxlength="32"
                :readonly="type === 'view'"
                :placeholder="$t('ENTER_RESOURCE_CODE')"
              />
              <el-popover width="200" trigger="hover" class="form-tips">
                <div class="text-color" v-html="$t('RESOURCE_CODE_TIPS')" />
                <i slot="reference" class="iconfont icon-AFSwenhao text-color" />
              </el-popover>
            </el-form-item>
            <el-form-item :label="$t('VENDOR')" prop="company">
              <el-input
                v-model="formData.company"
                maxlength="32"
                :readonly="type === 'view'"
                :placeholder="$t('PLEASE_ENTER_VENDOR')"
              />
            </el-form-item>
            <el-form-item :label="$t('BRAND')" prop="brand">
              <el-input
                v-model="formData.brand"
                maxlength="32"
                :readonly="type === 'view'"
                :placeholder="$t('PLEASE_ENTER_BRAND')"
              />
            </el-form-item>
            <el-form-item :label="$t('Z_END_REGIONAL_STATION_NAME')" prop="endStationId">
              <el-input v-model="formData.endStationId" class="hide" />
              <region-cascader
                class="block size-mini"
                :selected-ids="[formData.endStationId]"
                :clearable="false"
                :disabled="
                  type === 'view' ||
                    (type === 'mod' &&
                      (zStationData.status === 'CONSIGN' ||
                        zStationData.status === 'REPAIR'))
                "
                data-name="stationTree"
                @change="zStationChange"
              />
            </el-form-item>
            <el-form-item v-if="zRoomList.length" :label="$t('Z_END_ROOM_NAME')">
              <el-select
                v-model="formData.endRoomId"
                clearable
                :disabled="type === 'view'"
              >
                <el-option
                  v-for="item in zRoomList"
                  :key="item.regionId"
                  :value="item.regionId"
                  :label="item.label"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <template v-if="type === 'view'">
          <el-button size="mini" @click="close">{{ $t("CLOSE") }}</el-button>
        </template>
        <template v-else>
          <el-button size="mini" @click="close">{{ $t("CANCEL") }}</el-button>
          <el-button size="mini" type="primary" @click="$debounce(save)">{{
            $t("SAVE")
          }}</el-button>
        </template>
      </template>
    </el-dialog>
    <CableLevel
      :visible="showLevelEdit"
      @close="closeLevel"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import CableApi from '@/api/oen/CableApi'
  import RegionCascader from '@/components/RegionCascader'
  import CableLevel from './CableLevel'

  export default {
    components: { RegionCascader, CableLevel },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      data: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        showLevelEdit: false,
        formData: {
          capacity: '',
          cableLength: 1,
          startStationId: '',
          endStationId: '',
          startRoomId: '',
          endRoomId: '',
          cableLevel: '',
          cableType: '',
          cableNorm: '',
          fiberType: '',
          connNum: undefined,
          occupyNum: undefined,
          idleNum: undefined
        },
        aRoomList: [],
        zRoomList: [],
        aStationData: {},
        zStationData: {}
      }
    },

    computed: {
      ...mapGetters(['dictList', 'baseRegionList', 'customDictList']),
      dictCableLevelList() {
        return this.customDictList.filter(i => i.type === 'CABLE_LEVEL')
      },
      title() {
        const titles = {
          add: 'ADD_OPTICAL_CABLE',
          view: 'VIEW_OPTICAL_CABLE',
          mod: 'MODIFY_OPTICAL_CABLE'
        }
        return this.$t(titles[this.type])
      },
      rules() {
        // 清空表单验证信息
        this.$nextTick(() => {
          this.$refs.cableForm && this.$refs.cableForm.clearValidate()
        })
        return {
          cableName: [
            {
              required: true,
              message: this.$t('ENTER_CABLE_NAME'),
              trigger: 'blur'
            }
          ],
          cableLevel: [
            {
              required: true,
              message: this.$t('SELECT_CABLE_LEVEL'),
              trigger: 'blur'
            }
          ],
          cableType: [
            {
              required: true,
              message: this.$t('SELECT_CABLE_TYPE'),
              trigger: 'blur'
            }
          ],
          cableNorm: [
            {
              required: true,
              message: this.$t('SELECT_CABLE_SPE'),
              trigger: 'blur'
            }
          ],
          fiberType: [
            {
              required: true,
              message: this.$t('SELECT_FIBER_CORE_TYPE'),
              trigger: 'blur'
            }
          ],
          startStationId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('A_END_STATION_NAME'),
              trigger: 'change'
            }
          ],
          endStationId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('Z_END_STATION_NAME'),
              trigger: 'change'
            }
          ],
          capacity: [
            {
              required: true,
              message: this.$t('ENTER_NOMINA_CAPACITY'),
              trigger: 'blur'
            },
            {
              pattern: /(^[0-9]\d*$)/,
              message: this.$t('RANGE_MSG_ERROR', { msg: '0 ~ 1024' }),
              trigger: ['blur', 'change']
            },
            {
              validator: (valid, value, callback) => {
                if (Number(value) > 1024 || Number(value) < 0) {
                  callback(
                    new Error(this.$t('RANGE_MSG_ERROR', { msg: '0 ~ 1024' }))
                  )
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            }
          ],
          cableLength: [
            {
              required: true,
              message: this.$t('ENTER_CABLE_LENGTH'),
              trigger: 'blur'
            },
            {
              pattern: /^(0|([1-9]\d*))(\.\d{1,3})?$/,
              message: this.$t('ONLY_FLOAT', { count: 3 }),
              trigger: ['blur', 'change']
            },
            {
              validator: (rule, value, callback) => {
                if (value <= 0) {
                  callback(this.$t('ONLY_FLOAT', { count: 3 }))
                } else {
                  callback()
                }
              },
              trigger: ['blur', 'change']
            },
            {
              validator: (rule, value, callback) => {
                this.validatePort(
                  rule,
                  value,
                  callback,
                  this.$t('CABLE_LENGTH'),
                  999999
                )
              },
              trigger: ['blur', 'change']
            }
          ],
          idleNum: [
            {
              pattern: /(^[0-9]\d*$)/,
              message: this.$t('ONLY_INIT'),
              trigger: ['blur', 'change']
            },
            {
              validator: (rule, value, callback) => {
                this.validatePort(
                  rule,
                  value,
                  callback,
                  this.$t('NUMBER_IDLE'),
                  1024
                )
              },
              trigger: ['blur', 'change']
            }
          ],
          occupyNum: [
            {
              pattern: /(^[0-9]\d*$)/,
              message: this.$t('ONLY_INIT'),
              trigger: ['blur', 'change']
            },
            {
              validator: (rule, value, callback) => {
                this.validatePort(
                  rule,
                  value,
                  callback,
                  this.$t('NUMBER_TAKEUP'),
                  1024
                )
              },
              trigger: ['blur', 'change']
            }
          ],
          connNum: [
            {
              pattern: /(^[0-9]\d*$)/,
              message: this.$t('ONLY_INIT'),
              trigger: ['blur', 'change']
            },
            {
              validator: (rule, value, callback) => {
                this.validatePort(
                  rule,
                  value,
                  callback,
                  this.$t('CONNECTED_NUMBER'),
                  1024
                )
              },
              trigger: ['blur', 'change']
            }
          ]
        }
      }
    },
    created() {},
    methods: {
      aStationChange(data) {
        this.formData.startRoomId = ''
        this.aRoomList = this.baseRegionList.filter((i) => i.parentId === data)
        this.formData.startStationId = data
        this.aStationData =
          this.baseRegionList.find((i) => i.regionId === data) || {}
      },
      zStationChange(data) {
        this.formData.endRoomId = ''
        this.zRoomList = this.baseRegionList.filter((i) => i.parentId === data)
        this.formData.endStationId = data
        this.zStationData =
          this.baseRegionList.find((i) => i.regionId === data) || {}
      },
      open() {
        this.$nextTick(() => {
          this.$refs.cableForm && this.$refs.cableForm.clearValidate()
        })
        if (this.data.id) {
          this.formData = { ...this.$options.data().formData, ...this.data }
          this.formData.connNum = this.formData.connNum || undefined
          this.formData.occupyNum = this.formData.occupyNum || undefined
          this.formData.idleNum = this.formData.idleNum || undefined
          this.$nextTick(() => {
            this.formData.startRoomId = this.data.startRoomId
            this.formData.endRoomId = this.data.endRoomId
          })
        } else {
          this.formData = this.$options.data().formData
        }
      },
      save() {
        console.log('this.formData', this.formData)
        this.$refs.cableForm.validate((valid) => {
          if (valid) {
            CableApi[this.type](this.formData).then((result) => {
              if (result) {
                const success = this.$t('SAVE_SUCCESS')
                this.$message.success(success)
                this.close(true)
              }
            })
          }
        })
      },
      close(load) {
        this.formData = { ...this.$options.data().formData }
        this.$emit('close', load)
      },
      validatePort(rule, value, callback, name, max) {
        if (Number(value) > Number(max)) {
          callback(
            new Error(this.$t('PORT_CAPACITY_VALID', { msg1: name, msg2: max }))
          )
        } else {
          callback()
        }
      },
      closeLevel(data) {
        this.showLevelEdit = false
        this.$nextTick(() => {
        })
        if (data === true) {
          setTimeout(() => {
            this.$emit('reload', null)
          }, 2000)
        }
      }
    }
  }
</script>

<style scoped>
.edit-icon {
  font-size: 15px;
  line-height: 28px;
}
</style>
